package com.qinge.blog.controller;

import com.github.pagehelper.PageInfo;
import com.qinge.blog.entity.BlogUser;
import com.qinge.blog.utils.CurrentUserUtil;
import com.qinge.blog.service.*;
import com.qinge.blog.utils.result.JsonResult;
import com.qinge.blog.utils.result.ResultTool;
import com.qinge.blog.vo.BaseIdReqVO;
import com.qinge.blog.vo.BaseIdsReqVO;
import com.qinge.blog.vo.paging.PagingReqVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * @author QDW
 * @date 2022/4/28 13:36
 * @description 用户controller
 **/
@Api(tags={"登录"})
@RestController
@RequestMapping("/blog/api/user")
public class BlogUserController  {

    @Resource
    BlogUserService userService;

    @Resource
    BlogUserRoleService userRoleService;

    @Resource
    CaptchaService captchaService;


    @ApiOperation(value = "验证码",notes = "获取验证码图片")
    @GetMapping("/captcha")
    public JsonResult captcha() throws IOException {
        return ResultTool.success(captchaService.captchaCreator());
    }


    @GetMapping("/role/list")
    public JsonResult roles(){
        return ResultTool.success(userRoleService.findRolesByUserId(CurrentUserUtil.getUserId()));
    }

    @RequestMapping("/")
    public String hello(){
        return "Hello World";
    }

    @RequestMapping("/register")
    public JsonResult register(@RequestBody BlogUser user){
        userService.add(user);

        userRoleService.add(Collections.singletonList(user.getId()), Collections.singletonList("2"));
        return ResultTool.success();
    }

    @RequestMapping("/add")
    public JsonResult add(@RequestBody List<BlogUser> list){
        userService.addByList(list);

        return ResultTool.success();
    }

    @RequestMapping("/delete")
    public JsonResult delete(@RequestBody BaseIdsReqVO idsReqVO){
        userRoleService.removeByUserIds(idsReqVO.getIds());

        userService.removeBatchByIds(idsReqVO.getIds());

       return ResultTool.success();
    }

    @RequestMapping("/update")
    public JsonResult update(@RequestBody BlogUser list){
        userService.upsert(list);

        return ResultTool.success();
    }

    @RequestMapping("/find")
    public JsonResult find(@RequestBody BaseIdReqVO idReqVO){
        return ResultTool.success(userService.findById(idReqVO.getId()));
    }

    @RequestMapping("/paging")
    public JsonResult paging(@RequestBody PagingReqVO<BlogUser> pagingReqVO){

        PageInfo<BlogUser> iPage= userService.paging(pagingReqVO);

        userService.fillRoles(iPage.getList());

        return ResultTool.success(iPage);
    }

}
